//
//  GJFSingleTool.m
//  Wedding
//
//  Created by 郭静芬 on 2016/12/23.
//  Copyright © 2016年 郭静芬. All rights reserved.
//

#import "GJFSingleTool.h"
#import <CommonCrypto/CommonDigest.h>

@implementation GJFSingleTool

//创建单例
+ (GJFSingleTool *)shareInstance {
    static GJFSingleTool *single = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        single = [[GJFSingleTool alloc] init];
    });
    return single;
}
// 解档
- (instancetype)init
{
    self = [super init];
    if (self) {
        _userInfo = [NSKeyedUnarchiver unarchiveObjectWithFile:USERINFOPATH];
        if (!_userInfo) {
            _userInfo = [[GJFUserInfo alloc] init];
        }
    }
    return self;
}
//获取当前操作系统名称
+ (NSString *)os_name {
    return @"iOS";
}
//获取内测版本号
+ (NSString *)app_build {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
}
//获取发布版本号
+ (NSString *)app_version {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}
//获取通讯协议版本号
+ (NSString *)protocol_version {
    return @"1.1";
}

+ (BOOL)is_login {
    GJFUserInfo *userInfo = [GJFSingleTool shareInstance].userInfo;
    if (kStringIsEmpty(userInfo.token)) {
        return NO;
    }
    return YES;
}

#pragma mark - md5加密
+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

//归档
+ (void)saveUserInfo {
    [NSKeyedArchiver archiveRootObject:[[GJFSingleTool shareInstance] userInfo] toFile:USERINFOPATH];
}

//顶层的viewCotroller
+ (UIViewController*)topViewController {
    return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}
+ (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController*)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}
//绑定DeviceToken
+ (void)bingDeviceToken {
    if ([GJFSingleTool is_login]) {
        NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
        NSDictionary *dict = @{@"deviceToken":deviceToken?:@""};
        [GJFNetworkTool POSTRequestWithUrl:APP_MINE_DEVICETOKEN params:dict complete:^(NSDictionary *result) {}];
    }
}

/**
 *  显示弹框
 *
 *  @param title       标题
 *  @param msg         提示信息
 *  @param leftTitle   左边按钮的标题
 *  @param rightTitle  右边按钮的标题
 *  @param sec         自动消失的秒数.默认2秒
 *  @param leftBlock   点击左边的按钮触发的回调
 *  @param rightAction 点击右边的按钮触发的回调
 */
+ (void)showAlertTitle:(NSString *)title Message:(NSString *)msg leftTitle:(NSString *)leftTitle rightTitle:(NSString *)rightTitle delayTime:(NSInteger)sec leftAction:(LeftAction)leftBlock rightAction:(RightAction)rightAction {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    if (leftTitle) {
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:leftTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            if (leftBlock) {
                leftBlock();
            }
        }];
        [alertController addAction:cancelAction];
    }
    if (rightTitle) {
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:rightTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (rightAction) {
                rightAction();
            }
        }];
        [alertController addAction:okAction];
    }
    [[self topViewController] presentViewController:alertController animated:YES completion:^{
        if (leftTitle || rightTitle) {
            
        }
        else if (sec > 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alertController dismissViewControllerAnimated:YES completion:^{
                    
                }];
            });
        }
    }];
}

+ (void)shareToViewController:(UIViewController<UMSocialShareMenuViewDelegate> *)vc title:(NSString *)title content:(NSString *)content image:(UIImage *)image url:(NSString *)url {
    [UMSocialUIManager setShareMenuViewDelegate:vc];
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        // 根据获取的platformType确定所选平台进行下一步操作
        
        if (platformType == UMSocialPlatformType_Sina) {
            [[[GJFSingleTool topViewController] view] showWarning:@"暂未开启"];
            return;
        }
        //构造分项内容
        UMShareWebpageObject *webObject = [UMShareWebpageObject shareObjectWithTitle:title descr:content thumImage:image];
        webObject.webpageUrl = url;
        
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObjectWithMediaObject:webObject];
        //设置文本
        messageObject.text = content;
        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:vc completion:^(id data, NSError *error) {
            if (error) {
                NSLog(@"************分享失败的错误信息 %@*********",error);
                NSString *errorStr = [error.userInfo objectForKey:@"message"];
                if ([errorStr isEqualToString:@"Operation is canel"]) {
                    [[vc view] showWarning:@"取消分享"];
                }
            }else{
                NSLog(@"response data is %@",data);
                [[vc view] showWarning:@"分享成功"];
            }
        }];
    }];
}



#pragma mark - 自适应高度
+ (CGFloat)heightWithText:(NSString *)text fontSize:(CGFloat)fontsize Width:(CGFloat)width {
    // 设置一个字典保存文本属性
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]};
    // 预设尺寸 文本最大不会超过这个尺寸
    CGSize size = CGSizeMake(width, CGFLOAT_MAX);
    // 根据文本信息计算得到一个CGRECT
    // 参数1:尺寸范围
    // 参数2:获取文本尺寸的方式
    // 参数3:获取文本属性
    // 参数3:无用信息(上下文)
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return ceil(rect.size.height);
}

#pragma mark - 使用颜色填充图片
+ (UIImage *)imageWithColor:(UIColor *)color {
    // 描述矩形
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}
@end
